package com.orange.cas.server.config;

import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;

import org.apereo.cas.authentication.AuthenticationHandlerExecutionResult;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


public class Login extends AbstractUsernamePasswordAuthenticationHandler {
	
    private static final org.slf4j.Logger LOGGER =LoggerFactory.getLogger(Login.class);
    private String sql="select * from sec_user where account=?";

	public Login(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {
		super(name, servicesManager, principalFactory, order);
	}

	@Override
	protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(
			UsernamePasswordCredential credential, String originalPassword)
			throws GeneralSecurityException, PreventedException {
		DriverManagerDataSource d=new DriverManagerDataSource();
        d.setDriverClassName("com.mysql.jdbc.Driver");
        d.setUrl("jdbc:mysql://127.0.0.1:3306/ssm-shiro");
        d.setUsername("root");
        d.setPassword("root");
        JdbcTemplate template=new JdbcTemplate();
        template.setDataSource(d);
        
        String account = credential.getUsername();
        String password = credential.getPassword();
        LOGGER.info("登录信息>>>>>username:"+ account + ",password:"+password +", originalPassword:" + originalPassword);
        User user=template.queryForObject(sql, new Object[]{account}, new BeanPropertyRowMapper<User>(User.class));
        
        if(user == null){
        	throw new PreventedException("用户不存在", null);
        }
        if(!user.getPassword().equals(password)){
        	throw new PreventedException("用户或者密码错误", null);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", user.getAccount());
        map.put("id", user.getId());

        return createHandlerResult(credential, principalFactory.createPrincipal(account, map));
	}

}
